#include <vector>
#include <mutex>
#include <thread>
#include <chrono>
#include <random>
#include <functional>
#include <atomic>

namespace raft {

struct VoteRequest {
    int nodeId;
    int term;
    int lastLogIndex;  // Raft需要的字段
    int lastLogTerm;   // Raft需要的字段
};

struct VoteResponse {
    int nodeId;
    int term;
    bool voteGranted;
};

enum Role {
    FOLLOWER,
    CANDIDATE,
    LEADER
};

enum State {
    RUNNING,
    STOPPED
}; // 修复：添加分号

class Raft {
public:
    Raft(int nodeId, std::vector<int> nodes) {
        nodeId_ = nodeId;
        nodes_ = nodes;
        currentTerm_ = 0;
        votedFor_ = -1;
        maxElectionTimeout_ = 2000;
        minElectionTimeout_ = 1000;
        role_ = FOLLOWER;
        leaderId_ = -1;
        state_ = STOPPED;
        resetElectionTimeout();
    }

    void start() {
        {
            std::lock_guard<std::mutex> lock(mutex_raft_info_);
            state_ = RUNNING;
            resetElectionTimeout();
        }
        electionTimeoutThread_ = std::thread(&Raft::electionTimeoutLoop, this);
    }

    void stop() {
        {
            std::lock_guard<std::mutex> lock(mutex_raft_info_);
            state_ = STOPPED;
        }
        if (electionTimeoutThread_.joinable()) {
            electionTimeoutThread_.join();
        }
    }

    // 修复：正确的选举超时检查
    bool isElectionTimeout() {
        auto now = std::chrono::steady_clock::now();
        auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
            now - electionTimeoutStart_).count();
        return elapsed >= electionTimeout_;
    }

    void resetElectionTimeout() {
        electionTimeoutStart_ = std::chrono::steady_clock::now();
        electionTimeout_ = getRandomElectionTimeout();
    }

    void becomeFollower(int term) {
        if (term < currentTerm_) {
            return;
        }
        role_ = FOLLOWER;
        if (term > currentTerm_) {
            votedFor_ = -1;
            currentTerm_ = term;
        }
        resetElectionTimeout();
    }

    void becomeCandidate() {
        if (role_ == LEADER) {
            return;
        }
        currentTerm_++;
        votedFor_ = nodeId_;
        role_ = CANDIDATE;
        resetElectionTimeout();
    }

    void becomeLeader() {
        if (role_ != CANDIDATE) {
            return;
        }
        role_ = LEADER;
        leaderId_ = nodeId_;
        // TODO: 初始化nextIndex和matchIndex
        // TODO: 立即发送心跳
    }

    // 修复：简化选举逻辑
    void startElection() {
        std::lock_guard<std::mutex> lock(mutex_raft_info_);
        
        becomeCandidate();
        int currentElectionTerm = currentTerm_;
        
        // 为自己投票
        int voteCount = 1;
        
        // 异步向其他节点请求投票
        for (int nodeId : nodes_) {
            if (nodeId == nodeId_) continue;
            
            // 这里应该异步发送投票请求
            // 实际实现中需要网络模块支持
            std::thread([this, nodeId, currentElectionTerm, &voteCount]() {
                VoteRequest request;
                request.nodeId = nodeId_;
                request.term = currentElectionTerm;
                // TODO: 设置lastLogIndex和lastLogTerm
                
                // 模拟网络请求
                VoteResponse response = sendVoteRequestSync(nodeId, request);
                
                std::lock_guard<std::mutex> lock(mutex_raft_info_);
                
                // 检查是否还是候选人且term没变
                if (role_ != CANDIDATE || currentTerm_ != currentElectionTerm) {
                    return;
                }
                
                if (response.term > currentTerm_) {
                    becomeFollower(response.term);
                    return;
                }
                
                if (response.voteGranted) {
                    voteCount++;
                    if (voteCount > nodes_.size() / 2) {
                        becomeLeader();
                    }
                }
            }).detach(); // 注意：实际项目中应该管理这些线程
        }
    }

    // 处理投票请求
    VoteResponse handleVoteRequest(const VoteRequest& request) {
        std::lock_guard<std::mutex> lock(mutex_raft_info_);
        
        VoteResponse response;
        response.nodeId = nodeId_;
        response.term = currentTerm_;
        response.voteGranted = false;
        
        // 如果请求的term小于当前term，拒绝投票
        if (request.term < currentTerm_) {
            return response;
        }
        
        // 如果请求的term大于当前term，更新状态
        if (request.term > currentTerm_) {
            becomeFollower(request.term);
        }
        
        response.term = currentTerm_;
        
        // 投票逻辑：
        // 1. 还没投票给任何人，或者已经投票给了这个候选人
        // 2. 候选人的日志至少和自己一样新（这里简化了）
        if ((votedFor_ == -1 || votedFor_ == request.nodeId)) {
            votedFor_ = request.nodeId;
            response.voteGranted = true;
            resetElectionTimeout();
        }
        
        return response;
    }

private:
    void electionTimeoutLoop() {
        while (true) {
            {
                std::lock_guard<std::mutex> lock(mutex_raft_info_);
                if (state_ == STOPPED) break;
                
                // 只有Follower和Candidate需要检查选举超时
                if (role_ != LEADER && isElectionTimeout()) {
                    startElection();
                }
            }
            
            // 睡眠一小段时间，避免忙等待
            std::this_thread::sleep_for(std::chrono::milliseconds(50));
        }
    }

    int getRandomElectionTimeout() {
        static std::random_device rd;
        static std::mt19937 gen(rd());
        std::uniform_int_distribution<> dis(minElectionTimeout_, maxElectionTimeout_);
        return dis(gen);
    }

    // 模拟同步发送投票请求（实际应该是异步的）
    VoteResponse sendVoteRequestSync(int targetNodeId, const VoteRequest& request) {
        // 这里应该通过网络发送请求
        // 暂时返回一个模拟响应
        VoteResponse response;
        response.nodeId = targetNodeId;
        response.term = currentTerm_;
        response.voteGranted = (rand() % 2 == 0); // 随机投票，仅用于测试
        return response;
    }

public:
    // 成员变量
    std::mutex mutex_raft_info_;
    
    // 节点信息
    std::vector<int> nodes_;
    State state_;
    int nodeId_;
    
    // Raft状态
    int currentTerm_;
    int votedFor_;
    Role role_;
    int leaderId_;
    
    // 选举超时
    std::chrono::steady_clock::time_point electionTimeoutStart_;
    int electionTimeout_;
    int maxElectionTimeout_;
    int minElectionTimeout_;
    
    // 线程
    std::thread electionTimeoutThread_;
};

} // namespace raft
